<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref } from 'vue';

import { Input, Textarea, Select, RadioGroup, CheckboxGroup, DatePicker, Form, FormItem, Row, Col } from 'ant-design-vue';
import { ImageUpload, FileUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';

import { getDictOptions } from '#/utils/dict';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { orderAdd, orderInfo, orderUpdate } from '#/api/trade/order';
import type { OrderForm } from '#/api/trade/order/model';
import { useBeforeCloseDiff } from '#/utils/popup';
import SaleContractDetails from '../saleContract/components/SaleContractDetails.vue';
import { customerInfo } from '#/api/trade/customer';
import type { DefaultOptionType } from 'ant-design-vue/es/select';
import type { CustomerVO } from '#/api/trade/customer/model';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

// 客户信息
const customerDefault: Partial<CustomerVO> = {
  id: '',
  name: '',
  contact: '',
  contactPhone: '',
  saleUserid: '',
  areaType: '',
  provinceId: '',
  cityId: '',
  districtId: '',
  areaId: [],
  updateBy:0,
  updateTime:''
};

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<OrderForm> = {
  id: undefined,
  deptId: undefined,
  orderNo: undefined,
  saleContractId: undefined,
  saleContractDetailId: undefined,
  status: undefined,
  frameNo: undefined,
  logisticsPic: undefined,
  testReportPic: undefined,
  saleContract: {},
}

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);
const customerData = ref(customerDefault);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<OrderForm>>({
    code: [
      { required: true, message: "订单编号不能为空" }
    ],
    saleContractId: [
      { required: true, message: "销售合同不能为空" }
    ],
    saleContractDetailId: [
      { required: true, message: "销售合同明细不能为空" }
    ],
    status: [
      { required: true, message: "合同状态不能为空" }
    ],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[800px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await orderInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      //设置filterRecord.saleContract?.details[0]?.frameNo
      filterRecord.saleContract!.details[0]!.frameNo = record.frameNo;
      formData.value = filterRecord;
      
      // 获取客户信息来显示客户名称
      if (record.saleContract?.customerId) {
        try {
          const customerInfoData = await customerInfo(record.saleContract.customerId);
          if (customerInfoData) {
            customerData.value = customerInfoData;
          }
        } catch (error) {
          console.error('获取客户详情失败', error);
        }
      }
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value) as OrderForm;
    data.frameNo = data.saleContract?.details?.[0]?.frameNo;
   
    await (isUpdate.value ? orderUpdate(data) : orderAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  formData.value = defaultValues;
  // customerData.value = null;
  resetFields();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title" :width="800">
    <Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="订单编号" v-bind="validateInfos.code">
            <Input v-model:value="formData.orderNo" :placeholder="$t('ui.formRules.required')" disabled />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="客户名称">
            <Input v-model:value="customerData!.name" :placeholder="$t('ui.formRules.required')" disabled />
          </FormItem>
        </Col>
      </Row>
      
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="联系人">
            <Input v-model:value="formData.saleContract!.contact" :placeholder="$t('ui.formRules.required')" disabled />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="联系方式">
            <Input v-model:value="formData.saleContract!.contactPhone" :placeholder="$t('ui.formRules.required')" disabled />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <!-- 销售明细部分 -->
        <Col :span="24">
          <FormItem  :wrapper-col="{ span: 24 }" :label-col="{ span: 0 }">
            <SaleContractDetails v-model="formData.saleContract!.details!" :disabled="true" :showActions="false" :show-frame-no="true" :frameNoEditable = "true" />
          </FormItem>
        </Col>
      </Row>
      <!-- 图片上传字段单独占一行，因为需要更多空间 -->
      <Row>
        <Col :span="12">
          <FormItem label="物流信息" v-bind="validateInfos.logisticsPic" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <FileUpload 
              :max-count="1" 
              v-model:value="formData.logisticsPic"
              accept=".jpg,.jpeg,.png,.gif,.webp,.xlsx,.csv,.docx,.pdf"
            />
          </FormItem>
        </Col>
      
        <Col :span="12">
          <FormItem label="检测报告" v-bind="validateInfos.testReportPic" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <FileUpload 
              :max-count="1" 
              v-model:value="formData.testReportPic"
              accept=".jpg,.jpeg,.png,.gif,.webp,.xlsx,.csv,.docx,.pdf"
            />
          </FormItem>
        </Col>
      </Row>
    </Form>
  </BasicDrawer>
</template>

